package handler

import (
	"context"
	"coroutine/server/basic/config"
	"coroutine/server/basic/model"
	pb "coroutine/server/proto"
)

func (s *Server) AddTicket(_ context.Context, in *pb.AddTicketReq) (*pb.AddTicketResp, error) {
	var t model.Ticket
	config.DB.Debug().Where("ticket_id_card = ?", in.TicketIdCard).Limit(1).Find(&t)
	if t.Id != 0 {
		return &pb.AddTicketResp{
			Message: "该车次已存在",
			Code:    10001,
		}, nil
	}
	ticket := model.Ticket{
		TicketIdCard:      in.TicketIdCard,
		TicketType:        in.TicketType,
		TicketStart:       in.TicketStart,
		TicketState:       in.TicketState,
		TicketTrainNumber: in.TicketTrainNumber,
		TicketSeatType:    in.TicketSeatType,
		TicketNumber:      uint64(in.TicketNumber),
		TicketPrice:       float64(in.TicketPrice),
	}
	err := config.DB.Debug().Create(&ticket).Error
	if err != nil {
		return &pb.AddTicketResp{
			Message: "车票发布失败",
			Code:    10002,
		}, nil
	}
	return &pb.AddTicketResp{
		Message: "车票发布成功",
		Code:    200,
	}, nil
}
func (s *Server) UpdatedTicket(_ context.Context, in *pb.UpdatedTicketReq) (*pb.UpdatedTicketResp, error) {
	var t model.Ticket
	config.DB.Debug().Where("id = ?", in.Id).Limit(1).Find(&t)
	if t.Id == 0 {
		return &pb.UpdatedTicketResp{
			Message: "没有该车次",
			Code:    10001,
		}, nil
	}
	ticket := model.Ticket{
		Id:           in.Id,
		TicketNumber: uint64(in.TicketNumber),
	}
	err := config.DB.Debug().Updates(&ticket).Error
	if err != nil {
		return &pb.UpdatedTicketResp{
			Message: "车票补票失败",
			Code:    10002,
		}, nil
	}
	return &pb.UpdatedTicketResp{
		Message: "车票补票成功",
		Code:    200,
	}, nil
}
